﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
using Microsoft.VisualBasic.FileIO;
using System.Drawing;
using CommonLib.System.FileSystem;

namespace WinFileTransfer
{
    public partial class FrmMain : Form
    {
        #region construction
        public FrmMain()
        {
            InitializeComponent();
            m_SyncContext = SynchronizationContext.Current;
            splitMain.Panel2Collapsed = true;//分栏
            tstboxPwd.TextBox.UseSystemPasswordChar = true;//显示**
            _CurrentNativePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);//获取桌面路径
            InitializeNative(_CurrentNativePath);//初始目录树
            tsbtnNBackward.Enabled = false;//前进
            tsbtnNForeward.Enabled = false;//后退
            SetRemoteControlState(false);//远程目录树状态
            msMain.Visible = false;//可见
        }
        #endregion

        #region members
        private SynchronizationContext m_SyncContext;//同步上下文
        private NetworkShareAccesser _NetAccesser = null;//网络连接管理
        private bool _IsConnected = false;//连接状态
        private string _CurrentNativePath = null;
        private string _CurrentRemotePath = null;
        private Stack _NativeBackStack = new Stack();
        private Stack _NativeForeStack = new Stack();
        private Stack _RemoteBackStack = new Stack();
        private Stack _RemoteForeStack = new Stack();
        private ListViewItem lvContentItem = null;
        #endregion

        #region event

        #region connection toolstrip
        private void tstboxHost_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                tstboxUser.Focus();
            }
        }

        private void tstboxUser_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                tstboxPwd.Focus();
            }
        }

        private void tstboxPwd_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                tsbtnConnect.PerformClick();
            }
        }

        private void tsbtnConnect_Click(object sender, EventArgs e)
        {
            if (_IsConnected)
            {
                _NetAccesser.Dispose();
                _NetAccesser = null;
                _IsConnected = false;
                tsbtnConnect.Image = Properties.Resources.connect_close;
                tstboxShare.Text = "";
                SetRemoteControlState(false);
                _RemoteBackStack.Clear();
                _RemoteForeStack.Clear();
            }
            else
            {
                splitMain.Panel2Collapsed = false;
                lvInfo.Items.Clear();
                if (lvInfo.SmallImageList != null)
                    lvInfo.SmallImageList.Images.Clear();
                if (!String.IsNullOrWhiteSpace(tstboxHost.Text))// && !String.IsNullOrWhiteSpace(tstboxShare.Text))
                {
                    _CurrentRemotePath = @"\\" + tstboxHost.Text + "\\" + tstboxShare.Text;
                    try
                    {
                        _NetAccesser = NetworkShareAccesser.Access(tstboxHost.Text, tstboxUser.Text, tstboxPwd.Text);
                        FolderBrowserDialog folderBrowser = new FolderBrowserDialog() { SelectedPath = _CurrentRemotePath };//构造文件浏览对话框
                        if (folderBrowser.ShowDialog() != DialogResult.OK)
                        {
                            _NetAccesser.Dispose();
                            _NetAccesser = null;
                            return;
                        }
                        tstboxShare.Text = folderBrowser.SelectedPath.Substring(_CurrentRemotePath.Length);
                        _CurrentRemotePath = folderBrowser.SelectedPath;

                        InitializeRemote(_CurrentRemotePath);//初始化远程树
                        _IsConnected = true;//连接状态
                        tsbtnConnect.Image = Properties.Resources.connect_checkmark;
                        tstboxRDirectory.Enabled = true;
                        if (Directory.GetParent(_CurrentRemotePath) != null)
                            tsbtnRLastLevel.Enabled = true;
                        tsbtnRRefresh.Enabled = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, "请检查共享路径及用户名密码！", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _CurrentRemotePath = null;
                        LogHelper.Log.Error(ex);
                    }
                }
            }
        }
        #endregion

        #region context menu
        private void tsmiTransfer_Click(object sender, EventArgs e)//传输操作
        {
            try
            {
                TransferParams param = new TransferParams() { IsSingleFile = !lvContentItem.SubItems[2].Text.Equals("文件夹") };
                if (lvContentItem.ListView == lvNContent)//获取点击的是本地还是远程
                {
                    param.Source = _CurrentNativePath + "\\" + lvContentItem.Text;
                    param.Destination = _CurrentRemotePath;
                    param.IsFromNatice = true;
                }
                else
                {
                    param.Source = _CurrentRemotePath + "\\" + lvContentItem.Text;
                    param.Destination = _CurrentNativePath;
                    param.IsFromNatice = false;
                }
                Thread thread = new Thread((obj) =>
                {
                    TransferParams transferParams = (TransferParams)obj;
                    m_SyncContext.Post((o) =>
                    {
                        PerformTransfer(transferParams.Source, transferParams.Destination, transferParams.IsFromNatice, transferParams.IsSingleFile);
                    }, null);
                    if (transferParams.IsFromNatice)//刷新被传输的目录状态
                        m_SyncContext.Post((o) => { InitializeRemote((string)o); }, _CurrentRemotePath);
                    else
                        m_SyncContext.Send((o) => { InitializeNative((string)o); }, _CurrentNativePath);
                });
                thread.Start(param);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsmiCopy_Click(object sender, EventArgs e)
        {
            try
            {
                StringCollection fileList = new StringCollection();
                string path = null;
                if (lvContentItem.ListView == lvNContent)
                    path = _CurrentNativePath + "\\" + lvContentItem.Text;
                else
                    path = _CurrentRemotePath + "\\" + lvContentItem.Text;
                if (lvContentItem.SubItems[2].Text.Equals("文件夹"))
                    fileList.AddRange(FileUtil.GetFiles(path).ToArray());
                else
                    fileList.Add(path);
                Clipboard.SetFileDropList(fileList);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsmiRename_Click(object sender, EventArgs e)//重命名
        {
            FileInfo fileInfo = null;
            string path = null;
            try
            {
                if (lvContentItem.ListView == lvNContent)
                {
                    path = _CurrentNativePath + "\\" + lvContentItem.Text;
                    fileInfo = new FileInfo(path);
                    FrmRename frm = new FrmRename(fileInfo);
                    frm.ShowDialog();
                    InitializeNative(_CurrentNativePath);
                }
                else
                {
                    path = _CurrentRemotePath + "\\" + lvContentItem.Text;
                    fileInfo = new FileInfo(path);
                    FrmRename frm = new FrmRename(fileInfo);
                    frm.ShowDialog();
                    InitializeRemote(_CurrentRemotePath);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsmiDelete_Click(object sender, EventArgs e)//删除，默认放回收站
        {
            try
            {
                if (lvContentItem.ListView == lvNContent)
                {
                    string path = _CurrentNativePath + "\\" + lvContentItem.Text;
                    if (lvContentItem.SubItems[2].Text.Equals("文件夹"))
                        FileSystem.DeleteDirectory(path, UIOption.AllDialogs, RecycleOption.SendToRecycleBin);
                    else
                        FileSystem.DeleteFile(path, UIOption.AllDialogs, RecycleOption.SendToRecycleBin);
                    InitializeNative(_CurrentNativePath);
                }
                else
                {
                    string path = _CurrentRemotePath + "\\" + lvContentItem.Text;
                    if (lvContentItem.SubItems[2].Text.Equals("文件夹"))
                        FileSystem.DeleteDirectory(path, UIOption.AllDialogs, RecycleOption.SendToRecycleBin);
                    else
                        FileSystem.DeleteFile(path, UIOption.AllDialogs, RecycleOption.SendToRecycleBin);
                    InitializeRemote(_CurrentRemotePath);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsmiProperties_Click(object sender, EventArgs e)//显示属性
        {
            try
            {
                FileUtil.ShowProperties((lvContentItem.ListView == lvNContent ? _CurrentNativePath : _CurrentRemotePath) + "\\" + lvContentItem.Text);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }
        #endregion

        #region native
        private void lvNContent_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button != MouseButtons.Right)
                    return;
                lvContentItem = lvNContent.GetItemAt(e.X, e.Y);
                SetContextMenuState(true);
                cmenu.Show(lvNContent, e.Location);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void lvNContent_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = lvNContent.GetItemAt(e.X, e.Y);
            string path = _CurrentNativePath + (_CurrentNativePath.EndsWith("\\") ? "" : "\\") + item.Text;
            try
            {
                if (item.SubItems[2].Text.Equals("文件夹"))
                {
                    InitializeNative(path);
                    _NativeBackStack.Push(_CurrentNativePath);
                    _CurrentNativePath = path;
                    tsbtnNBackward.Enabled = true;
                    if (Directory.GetParent(path) != null)
                        tsbtnNLastLevel.Enabled = true;
                }
                else if (item.SubItems[2].Text.ToUpper().Equals("SHORTCUT"))
                {
                    IWshRuntimeLibrary.IWshShell_Class shell = new IWshRuntimeLibrary.IWshShell_Class();
                    if (File.Exists(path) == true)
                    {
                        IWshRuntimeLibrary.IWshShortcut shortcut = shell.CreateShortcut(path) as IWshRuntimeLibrary.IWshShortcut;
                        if (shortcut != null)
                        {
                            InitializeNative(shortcut.TargetPath);
                            _NativeBackStack.Push(_CurrentNativePath);
                            _CurrentNativePath = shortcut.TargetPath;
                            tsbtnNBackward.Enabled = true;
                            if (Directory.GetParent(shortcut.TargetPath) != null)
                                tsbtnNLastLevel.Enabled = true;
                        }
                    }
                }
                else
                {
                    if (_IsConnected)
                    {
                        PerformTransfer(path, _CurrentRemotePath, true);
                        InitializeRemote(_CurrentRemotePath);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsbtnNBackward_Click(object sender, EventArgs e)
        {
            try
            {
                string path = (string)_NativeBackStack.Pop();
                InitializeNative(path);
                _NativeForeStack.Push(_CurrentNativePath);
                _CurrentNativePath = path;
                tsbtnNForeward.Enabled = true;
                if (_NativeBackStack.Count == 0)
                    tsbtnNBackward.Enabled = false;
                if (Directory.GetParent(path) != null)
                    tsbtnNLastLevel.Enabled = true;
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsbtnNForeward_Click(object sender, EventArgs e)
        {
            try
            {
                string path = (string)_NativeForeStack.Pop();
                InitializeNative(path);
                _NativeBackStack.Push(_CurrentNativePath);
                _CurrentNativePath = path;
                tsbtnNBackward.Enabled = true;
                if (_NativeForeStack.Count == 0)
                    tsbtnNForeward.Enabled = false;
                if (Directory.GetParent(path) != null)
                    tsbtnNLastLevel.Enabled = true;
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsbtnNLastLevel_Click(object sender, EventArgs e)
        {
            try
            {
                DirectoryInfo info = Directory.GetParent(_CurrentNativePath);
                _NativeBackStack.Push(_CurrentNativePath);
                tsbtnNBackward.Enabled = true;
                _CurrentNativePath = info.FullName;
                InitializeNative(_CurrentNativePath);
                if (info.Parent == null)
                    tsbtnNLastLevel.Enabled = false;
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsbtnNRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                _CurrentNativePath = tstboxNDirectory.Text;
                InitializeNative(_CurrentNativePath);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tstboxNDirectory_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == '\r')
                {
                    e.Handled = true;
                    string path = tstboxNDirectory.Text;
                    if (Directory.Exists(path))
                    {
                        InitializeNative(path);
                        _CurrentNativePath = path;
                    }
                    else
                    {
                        MessageBox.Show("不存在该目录！", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        tstboxNDirectory.SelectAll();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }
        #endregion

        #region remote

        private void lvRContent_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button != MouseButtons.Right)
                    return;
                SetContextMenuState(_IsConnected);
                lvContentItem = lvRContent.GetItemAt(e.X, e.Y);
                cmenu.Show(lvRContent, e.Location);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void lvRContent_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (!_IsConnected)
                return;
            ListViewItem item = lvRContent.GetItemAt(e.X, e.Y);
            string path = _CurrentRemotePath + "\\" + item.Text;
            try
            {
                if (item.SubItems[2].Text.Equals("文件夹"))
                {
                    InitializeRemote(path);
                    _RemoteBackStack.Push(_CurrentRemotePath);
                    _CurrentRemotePath = path;
                    tsbtnRBackward.Enabled = true;
                    if (Directory.GetParent(path) != null)
                        tsbtnRLastLevel.Enabled = true;
                }
                else
                {
                    PerformTransfer(path, _CurrentNativePath, false);
                    InitializeNative(_CurrentNativePath);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
                MessageBox.Show(String.Format("您可能没有权限访问该路径：\r\n{0}", path), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsbtnRBackward_Click(object sender, EventArgs e)
        {
            try
            {
                string path = (string)_RemoteBackStack.Pop();
                InitializeRemote(path);
                _RemoteForeStack.Push(_CurrentRemotePath);
                _CurrentRemotePath = path;
                tsbtnRForeward.Enabled = true;
                if (_RemoteBackStack.Count == 0)
                    tsbtnRBackward.Enabled = false;
                if (Directory.GetParent(path) != null)
                    tsbtnRLastLevel.Enabled = true;
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsbtnRForeward_Click(object sender, EventArgs e)
        {
            try
            {
                string path = (string)_RemoteForeStack.Pop();
                InitializeRemote(path);
                _RemoteBackStack.Push(_CurrentRemotePath);
                _CurrentRemotePath = path;
                tsbtnRBackward.Enabled = true;
                if (_RemoteForeStack.Count == 0)
                    tsbtnRForeward.Enabled = false;
                if (Directory.GetParent(path) != null)
                    tsbtnRLastLevel.Enabled = true;
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsbtnRLastLevel_Click(object sender, EventArgs e)
        {
            if (!_IsConnected)
                return;
            try
            {
                DirectoryInfo info = Directory.GetParent(_CurrentRemotePath);
                _RemoteBackStack.Push(_CurrentRemotePath);
                tsbtnRBackward.Enabled = true;
                _CurrentRemotePath = info.FullName;
                InitializeRemote(_CurrentRemotePath);
                if (info.Parent == null)
                    tsbtnRLastLevel.Enabled = false;
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tsbtnRRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                _CurrentRemotePath = tstboxRDirectory.Text;
                InitializeRemote(_CurrentRemotePath);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }

        private void tstboxRDirectory_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == '\r')
                {
                    e.Handled = true;
                    string path = tstboxRDirectory.Text;
                    if (Directory.Exists(path))
                    {
                        InitializeRemote(path);
                        _CurrentRemotePath = path;
                    }
                    else
                    {
                        MessageBox.Show("不存在该目录！", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        tstboxRDirectory.SelectAll();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
        }
        #endregion

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)//关闭窗口
        {
            if (_NetAccesser != null)
                try
                {
                    _NetAccesser.Dispose();
                }
                catch (Exception ex)
                {
                    LogHelper.Log.Error(ex);
                }
            this.Dispose();
        }
        #endregion

        #region private methods

        /// <summary>
        /// 设置右键菜单的状态
        /// </summary>
        /// <param name="enabled"></param>
        private void SetContextMenuState(bool enabled)
        {
            tsmiTransfer.Enabled = _IsConnected;//未连接时不可用
            tsmiCopy.Enabled = enabled;
            tsmiRename.Enabled = enabled;
            tsmiDelete.Enabled = enabled;
            tsmiProperties.Enabled = enabled;
        }

        /// <summary>
        /// 设置远程端各控件的可用状态
        /// </summary>
        /// <param name="enabled"></param>
        private void SetRemoteControlState(bool enabled)
        {
            tsbtnRBackward.Enabled = enabled;
            tsbtnRForeward.Enabled = enabled;
            tsbtnRLastLevel.Enabled = enabled;
            tsbtnRRefresh.Enabled = enabled;
            tstboxRDirectory.Enabled = enabled;
        }

        /// <summary>
        /// 重置本地目录列表
        /// </summary>
        /// <param name="path"></param>
        private void InitializeNative(string path)//
        {
            FillListView(lvNContent, path);
            tstboxNDirectory.Text = path;
        }

        /// <summary>
        /// 重置远程目录列表
        /// </summary>
        /// <param name="path"></param>
        private void InitializeRemote(string path)//
        {
            FillListView(lvRContent, path);
            tstboxRDirectory.Text = path;
        }

        /// <summary>
        /// 执行文件传输
        /// </summary>
        /// <param name="sourceFile">所选文件（或目录）</param>
        /// <param name="destFolder">目标目录</param>
        /// <param name="isFromNative">true=>从本地传输到远程主机，false=>从远程传输到本地</param>
        /// <param name="isSingleFile">true=>传输单个文件，false=>传输整个文件夹</param>
        private void PerformTransfer(string sourceFile, string destFolder, bool isFromNative = true, bool isSingleFile=true)//
        {
            ListViewItem lvInfoItem = null;
            try
            {
                if (isSingleFile)//传文件
                {
                    FileInfo fileInfo = new FileInfo(sourceFile);//获取文件信息
                    string destFile = destFolder + Path.DirectorySeparatorChar + fileInfo.Name;
                    if (File.Exists(destFile)//同名冲突
                                    && MessageBox.Show("该目录下已存在同名文件，是否覆盖？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                        return;
                    ImageList imageList = lvInfo.SmallImageList ?? new ImageList();//文件图标
                    lvInfo.SmallImageList = imageList;
                    imageList.Images.Add(sourceFile, isFromNative ? lvNContent.SmallImageList.Images[lvNContent.FocusedItem.ImageIndex] : lvRContent.SmallImageList.Images[lvRContent.FocusedItem.ImageIndex]);
                    lvInfoItem = AddListViewItem(lvInfo, new string[] { fileInfo.Name, "进行中", "0/1"
                        , FileUtil.GetFileSize(fileInfo.Length), isFromNative ? sourceFile : destFile, isFromNative ? destFile : sourceFile }, imageList.Images.Count - 1);
                    File.Copy(sourceFile, destFile, true);
                    lvInfoItem.SubItems[2].Text = "1/1";//进度
                }
                else//传文件夹
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(sourceFile);
                    ImageList imageList = lvInfo.SmallImageList ?? new ImageList();
                    lvInfo.SmallImageList = imageList;
                    imageList.Images.Add(sourceFile, isFromNative ? lvNContent.SmallImageList.Images[lvNContent.FocusedItem.ImageIndex] : lvRContent.SmallImageList.Images[lvRContent.FocusedItem.ImageIndex]);
                    lvInfoItem = AddListViewItem(lvInfo, new string[] { directoryInfo.Name, "进行中", "0/0"
                        , "--", isFromNative ? sourceFile : destFolder, isFromNative ? destFolder : sourceFile }, imageList.Images.Count - 1);
                    lvInfo.Refresh();

                    long fileLength = 0;//已传输对象的总大小
                    List<string> fileList = FileUtil.GetFiles(sourceFile);
                    List<string>[] failureList = new List<string>[] { new List<string>(), new List<string>() };
                    foreach (string file in fileList)
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        fileLength += fileInfo.Length;
                        lvInfoItem.SubItems[3].Text = FileUtil.GetFileSize(fileLength);
                        FileInfo destFileInfo = new FileInfo(destFolder + file.Substring(file.IndexOf(sourceFile) + Directory.GetParent(sourceFile).FullName.Length));
                        if (!destFileInfo.Directory.Exists)
                            destFileInfo.Directory.Create();
                        if (destFileInfo.Exists)
                        {
                            failureList[0].Add(file);
                            failureList[1].Add(destFileInfo.FullName);
                            continue;
                        }
                        File.Copy(file, destFileInfo.FullName, false);
                        lvInfoItem.SubItems[2].Text = String.Format("{0}/{1}", fileList.IndexOf(file) + 1 - failureList[0].Count, fileList.Count);
                        lvInfo.Refresh();
                    }

                    if (failureList[0].Count > 0 && MessageBox.Show(String.Format("该目录下已存在{0}个同名文件，是否覆盖？", failureList[0].Count)
                            , "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        string tmp = lvInfoItem.SubItems[2].Text;
                        int status = Int32.Parse(tmp.Substring(0, tmp.IndexOf('/')));
                        for (int i = 0; i < failureList[0].Count; i++)
                        {
                            File.Copy(failureList[0][i], failureList[1][i], true);
                            lvInfoItem.SubItems[2].Text = String.Format("{0}/{1}", ++status, fileList.Count);
                            lvInfo.Refresh();
                        }
                    }
                }
                lvInfoItem.SubItems[1].Text = "已完成";
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
                if (lvInfoItem != null)
                    lvInfoItem.SubItems[1].Text = "传输失败";
                MessageBox.Show(String.Format("你可能没有权限访问该路径或文件：\r\n{0}", sourceFile), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            lvInfo.Refresh();
        }

        /// <summary>
        /// 填充目录列表
        /// </summary>
        /// <param name="listView"></param>
        /// <param name="path"></param>
        private void FillListView(ListView listView, string path)//
        {
            Cursor.Current = Cursors.WaitCursor;
            listView.Items.Clear();
            ImageList imageList = listView.SmallImageList ?? new ImageList();//显示的图标
            imageList.Images.Clear();
            listView.SmallImageList = imageList;
            try
            {
                string[] directories = Directory.GetDirectories(path);//子目录 获取文件夹
                string[] files = Directory.GetFiles(path);//获取文件
                DirectoryInfo directoryInfo;
                foreach (string directory in directories)
                {
                    directoryInfo = new DirectoryInfo(directory);
                    if (!ValidatePath(directoryInfo))
                        continue;
                    imageList.Images.Add(directory, SystemIcon.GetSysIcon(directoryInfo).ToBitmap());
                    AddListViewItem(listView
                        , new string[] { directoryInfo.Name, "", "文件夹", directoryInfo.LastWriteTime.ToString("yyyy/MM/dd,H:mm") }
                        , imageList.Images.Count - 1);
                }
                FileInfo fileInfo;
                foreach (string file in files)
                {
                    fileInfo = new FileInfo(file);//获取文件信息
                    imageList.Images.Add(file, SystemIcon.GetSysIcon(fileInfo).ToBitmap());//文件名转换位图
                    AddListViewItem(listView, new string[] { fileInfo.Name//文件名
                        , fileInfo.Extension.Equals(".lnk") ? "" : FileUtil.GetFileSize(fileInfo.Length)//快捷方式不显示大小
                        , FileUtil.GetFileType(fileInfo.Extension)//扩展名
                        , fileInfo.LastWriteTime.ToString("yyyy/MM/dd,H:mm") }//更新日期
                        , imageList.Images.Count - 1);//序号
                }
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error(ex);
            }
            Cursor.Current = Cursors.Default;
        }

        private Boolean ValidatePath(DirectoryInfo directoryInfo)//目录过滤类似回收站不显示
        {
            Boolean ret;
            switch (directoryInfo.Name.ToUpper())
            {
                case "RECYCLER":
                case "RECYCLED":
                case "SYSTEM VOLUME INFORMATION":
                case "$RECYCLE.BIN":
                    ret = false;
                    break;
                default:
                    ret = true;
                    break;
            }
            return ret;
        }

        /// <summary>
        /// 向ListView中添加一个item
        /// </summary>
        /// <param name="listView"></param>
        /// <param name="subItems">每个SubItem的显示文本</param>
        /// <param name="imageIndex">图标索引,值为-1时表示无图标</param>
        /// <returns></returns>
        private ListViewItem AddListViewItem(ListView listView, string[] subItems, int imageIndex = -1)
        {
            ListViewItem lvItem = null;
            if (subItems != null || subItems.Length > 0)
            {
                lvItem = listView.Items.Add(subItems[0]);
                for (int i = 1; i < subItems.Length; i++)
                    lvItem.SubItems.Add(subItems[i]);
                lvItem.ImageIndex = imageIndex;
            }
            return lvItem;
        }
        
        #endregion

        #region class
        private class TransferParams
        {
            public String Source { get; set; }
            public String Destination { get; set; }
            public Boolean IsFromNatice { get; set; }
            public Boolean IsSingleFile { get; set; }
        }
        #endregion

    }
}
